package br.com.roteador.localizacao;

import java.util.Date;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.caelum.vraptor.Consumes;
import br.com.caelum.vraptor.Controller;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.view.Results;
import br.com.roteador.component.AcessSession;
import br.com.roteador.controller.BasicController;

@Controller
public class LocalizacaoController extends BasicController {
	@Inject private Result result;
	@Inject AcessSession acessSession;
	@Inject LocalizacaoMongoDAO localizacaoMondoDAO;
	@Inject LocalizacaoDAO localizacaoDAO;
	@Inject LocalizacaoService service;
	@Inject HttpServletRequest request; 
	@Inject HttpServletResponse response;
	
	@Consumes("application/json")
	@Post
    @Path(value = "/localizacao")
	public void localizacao(Localizacao localizacao) {
    	setSession(acessSession);
    	injetaUsuario();
    	//Grava no MONGODB.
    	//localizacaoMondoDAO.insertLocalizacoes(latitude, longitude, imei);
    	localizacao.setDataHora(new Date());
    	localizacaoDAO.save(localizacao);
    	
    	//response.setContentType("text/event-stream");
		//response.setCharacterEncoding("UTF-8");
		//request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
        //ServletContext appScope = request.getServletContext();
        /*Queue<Localizacao> listaLocalizacao = (Queue<Localizacao>)appScope.getAttribute("listaLocalizacao");
        if(listaLocalizacao != null){
        	listaLocalizacao.add(localizacao);
        }*/
          
        //enviaMensagens(localizacao);
    	service.processoNovaLocalizacao(localizacao);
    	Boolean retorno = true;
    	result.use(Results.json()).withoutRoot().from(retorno).serialize();
    }
	
	/*private void enviaMensagens(Localizacao localizacao){
		ServletContext appScope = request.getServletContext();
		final Executor watcherExecutor = Executors.newCachedThreadPool();
		Map<String, List<AsyncContext>> observadores = (Map<String, List<AsyncContext>>) appScope.getAttribute("observadores");
		 List<AsyncContext> watchers = observadores.get(localizacao.getImei());
		 if(watchers != null){
			 for(final AsyncContext aCtx : watchers){
				 watcherExecutor.execute(new Runnable(){
					 public void run() {
						 try {
							 PrintWriter writer = aCtx.getResponse().getWriter();
							 writer.write("data: " + localizacao.getImei() + " \n\n");
						     writer.flush();
						 } catch (IOException e) {
							 e.printStackTrace();
						 }
					 };
				 });
			 }
		 }
	}*/
    
	protected void redirect() {
		result.redirectTo(LocalizacaoController.class).index();
	}

	private void index() {}

}